#!/data/Software/mydan/perl/bin/perl -I/data/Software/mydan/CI/lib -I/data/Software/mydan/CI/private/lib
use strict;
use warnings;
use JSON;
use Logs;
use LWP::UserAgent;
use Encode;
use Util;
use FindBin qw( $RealBin );

$| ++;

=head1 SYNOPSIS

    db => $mysql,
    logs => 日志对象
=cut

return sub
{
    my %param = @_;
    my ( $logs, $projectid, $uuid, $excuteflow, $version ) = @param{qw( logs projectid uuid excuteflow version )};
    print '=' x 75, "\n";
    print "excuteflow($param{excuteflow})...\n";
    my $tagger = `cat '$RealBin/../logs/build_temp_uuid/$uuid/info/tagger'`;
    chomp $tagger;
    my $taginfo = `cat '$RealBin/../logs/build_temp_uuid/$uuid/info/taginfo'`;
    chomp $taginfo;
    Encode::_utf8_on($taginfo);

    $logs = Logs->new( 'code.build.send.excuteflow' ) unless $logs;

    my $ua = LWP::UserAgent->new();
    $ua->agent('Mozilla/9 [en] (Centos; Linux)');

    #HTTP::Message content must be bytes at
    my $bytes = encode_utf8($param{excuteflow}); 
    $excuteflow = $bytes;
    $bytes = encode_utf8($taginfo); 
    $taginfo = $bytes;

    my %env = eval{ Util::envinfo( qw( appkey appname envname envname.flow ) )};
    $logs->die( "fromat error $@" ) if $@;

    $ua->default_header( map{ $_ => $env{$_} }qw( appname appkey) );
 
    $ua->timeout( 10 );
    $ua->default_header ( 'Cache-control' => 'no-cache', 'Pragma' => 'no-cache' );

    my $url = "http://api.flow.open-c3.org/v1/plugin/flow_start";
    my $res = $ua->post( $url, 
    Content => JSON::to_json( +{ flow_name => $excuteflow, email => $tagger, projectid => $projectid, inputs => +{ version => $version, taginfo =>$taginfo, ci => "n-$env{envname}" } } ), 
    'Content-Type' => 'application/json' 
    );

    my $cont = $res->content;
    $logs->die( "excuteflow fail: $cont" ) unless $res->is_success;

    my $data = eval{JSON::from_json $cont};
    $logs->die( "excuteflow fail: $cont : no json $@" ) if $@;

    $logs->die( "excuteflow fail: $cont : stat fail" )  unless $data->{stat};

    printf "call flow ok: flowuuid:%s\n", $data->{data};
}
